<?php

namespace addons\twostep;

use app\admin\library\Auth;
use app\common\library\Auth as UserAuth;
use app\common\library\Menu;
use think\Addons;
use think\Config;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;
use think\Cookie;
use addons\twostep\library\SafeCode;

load_trait('controller/Jump');

/**
 * 插件
 */
class Twostep extends Addons
{
    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        $menu = [
            [
                'name' => 'general/twostep',
                'title' => '两步验证',
                'ismenu' => 1,
                'icon' => 'fa fa-shield',
                'sublist' => [
                    ['name' => 'general/twostep/index', 'title' => '查看'],
                    ['name' => 'general/twostep/cancel', 'title' => '取消动态口令'],
                    ['name' => 'general/twostep/remove', 'title' => '移除安全密钥'],
                    ['name' => 'general/twostep/totp', 'title' => '设置动态口令'],
                    ['name' => 'general/twostep/webauthn', 'title' => '设置安全密钥']
                ],
            ]
        ];
        Menu::create($menu, 'general');
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        Menu::delete('general/twostep');
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        Menu::enable('general/twostep');
        return true;
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        Menu::disable('general/twostep');
        return true;
    }

    /**
     * 用户登录验证
     * @return bool
     */
    use \traits\controller\Jump;

    public function userLoginSuccessed($user)
    {
        $request = Request::instance();
        $module_name = $request->module();
        $key = Config::get('token.key');
        $twostep_login = Cookie::get('twostep_login');
        $twostep_login = SafeCode::authCode($twostep_login, 'DECODE', $key);
        $conf = get_addon_config('twostep');
        $auth = UserAuth::instance();
        if (isset($conf['index']) && $conf['index'] == 1 && $module_name == "index") {
            if (empty($twostep_login) || $twostep_login == "0" || $twostep_login != "1") {
                Cookie::delete('twostep_login');
                Cookie::delete('twostep_uid');
                $check = Db::name('twostep')
                    ->where('user_id', $user->id)
                    ->where('isadmin', '=', 0)
                    ->find();
                if ($check && ($check['secret'] || $check['webauthndata'])) {
                    $auth->logout();//先退出进入验证页
                    Cookie::set('twostep_uid', $user->id);//设置
                    $this->success(__('正在跳转到两步验证'), url('index/twostep/login'));
                }
            }
        }
    }

    /**
     * 后台管理员登录验证
     */
    public function adminLoginAfter(&$request)
    {
        $twostep_login = Session::get('twostep_admin_login');
        $conf = get_addon_config('twostep');
        $auth = Auth::instance();
        if (isset($conf['admin']) && $conf['admin'] == 1) {
            if (empty($twostep_login) || $twostep_login == "0" || $twostep_login != "1") {
                Session::delete('twostep_admin_login');
                Session::delete('twostep_adminid');
                $username = $request->post('username');
                $password = $request->post('password');
                $keeplogin = $request->post('keeplogin');
                $uid = Db::name('admin')
                    ->where('username', $username)
                    ->find();
                $uid = $uid['id'];
                $check = Db::name('twostep')
                    ->where('user_id', $uid)
                    ->where('isadmin', '=', 1)
                    ->find();
                if ($check && ($check['secret'] || $check['webauthndata'])) {
                    $auth->logout();//先退出进入验证页
                    Session::set('twostep_adminid', $uid);//设置
                    Session::set('twostep_username', $username);//设置
                    Session::set('twostep_password', $password);//设置
                    Session::set('twostep_keeplogin', $keeplogin);//设置
                    $this->success(__('正在跳转到两步验证'), url('general/twostep/login'), ['url' => url('general/twostep/login'), 'id' => $uid, 'username' => $username, 'avatar' => '']);
                }
            }
        }
    }

    /**
     * 用户退出后清除状态
     */
    public function userLogoutSuccessed()
    {
        Cookie::delete('twostep_login');
        Cookie::delete('twostep_uid');
    }

    /**
     * 管理员退出后清除状态
     */
    public function adminLogoutAfter()
    {
        Session::delete('twostep_admin_login');
        Session::delete('twostep_adminid');
        Session::delete('twostep_username');
        Session::delete('twostep_password');
        Session::delete('twostep_keeplogin');
    }

    /**
     * 会员中心边栏
     * @return mixed
     * @throws \Exception
     */
    public function userSidenavAfter()
    {
        $request = Request::instance();
        $controllername = Loader::parseName($request->controller());
        $data = [
            'controllername' => $controllername
        ];
        return $this->fetch('view/hook/user_sidenav_after', $data);
    }

    /**
     * 应用初始化 引入CBOR phpseclib
     */
    public function appInit()
    {
        \think\Loader::addNamespace('CBOR', ADDON_PATH . 'twostep' . DS . 'library' . DS . 'CBOR' . DS);
        \think\Loader::addNamespace('phpseclib', ADDON_PATH . 'twostep' . DS . 'library' . DS . 'phpseclib' . DS);
    }
}
